<script setup>
import { ref, onMounted } from "vue";
import { supportsLocalStorage } from "@/lib/utils";
import { get, set } from "tiny-cookie";

let installEvent;
const storageName = "install-prompt";

const isOpen = ref(false);

const supportsStorage = supportsLocalStorage();

const getVisited = () => {
  if (supportsStorage) {
    return localStorage.getItem(storageName);
  } else {
    return get(storageName);
  }
};

const setVisited = () => {
  if (supportsStorage) {
    localStorage.setItem(storageName, true);
  } else {
    set(storageName, true);
  }
};

const handleClose = () => {
  setVisited();
  isOpen.value = false;
  installEvent = null;
};

onMounted(() => {
  window.addEventListener("beforeinstallprompt", (e) => {
    e.preventDefault();
    if (!getVisited()) {
      installEvent = e;
      isOpen.value = true;
    }
  });
});

const install = () => {
  isOpen.value = false;
  installEvent.prompt();
  installEvent.userChoice.then((choiceResult) => {
    if (choiceResult.outcome !== "accepted") {
      setVisited();
    }
    installEvent = null;
  });
};
</script>
<template>
  <div v-if="isOpen" class="text-sm text-white bg-secondary flex">
    <p class="flex-1 p-[15px] md:p-[15px_20px]">
      Do you want to
      <a class="underline" href="#" @click.prevent="install"
        >add this app to your home screen?</a
      >
    </p>
    <button
      class="flex flex-[0_0_auto] items-center px-[30px] bg-none border-l border-black border-solid"
      type="button"
      aria-label="Close"
      @click="handleClose"
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="15"
        height="15"
        viewBox="0 0 15 15"
      >
        <g
          fill="none"
          stroke="#fff"
          stroke-linecap="round"
          stroke-miterlimit="10"
          stroke-width="1.5"
        >
          <path d="M.75.75l13.5 13.5M14.25.75L.75 14.25" />
        </g>
      </svg>
    </button>
  </div>
</template>
